package me.spring.cloud.common.components.ips.common;

import cn.hutool.http.HttpRequest;
import me.spring.cloud.common.components.util.json.JsonUtil;

public class IpLocationUtil {

  private static String url = "https://whois.pconline.com.cn/ipJson.jsp?json=true&ip=";

  public static String[] getLocation(String ip) {
    String response = HttpRequest.get(url + ip).timeout(10000).execute().body();
    if (null != response && !"".equals(response)) {
      response = toJsonString(response);
      response = response.replaceAll("\\\\","");
      IpLocationResp gd = JsonUtil.parseJson(response, IpLocationResp.class);
      String[] location = new String[5];
      if (null != gd.getPro()) {
        location[0] = gd.getPro().trim();
      }
      if (null != gd.getCity()) {
        location[1] = gd.getCity().trim();
      }
      if (null != gd.getRegion()) {
        location[2] = gd.getRegion().trim();
      }
      if (null != gd.getAddr()) {
        location[3] = gd.getAddr().trim().replaceAll(" ","");
        location[4] = location[3];
      }
      if(!"".equals(location[3])){
        location[3] = location[3].replaceAll(location[0], "")
            .replaceAll(location[1], "").replaceAll(location[2], "");

      }
      return location;
    }
    return null;
  }

  private static String toJsonString(String s) {
    char[] tempArr = s.toCharArray();
    int tempLength = tempArr.length;
    for (int i = 0; i < tempLength; i++) {
      if (tempArr[i] == ':' && tempArr[i + 1] == '"') {
        for (int j = i + 2; j < tempLength; j++) {
          if (tempArr[j] == '"') {
            if (tempArr[j + 1] != ',' && tempArr[j + 1] != '}') {
              tempArr[j] = '”';
            } else if (tempArr[j + 1] == ',' || tempArr[j + 1] == '}') {
              break;
            }
          }
        }
      }
    }
    return new String(tempArr);
  }
}
